<script setup lang="ts">
import type { OptionsType } from "plus-pro-components";
import type { TreeInstance } from "element-plus";
import { reactive, ref } from "vue";
import { message } from "@/utils/message";
import $request from "./utils/request";

// 定义事件
const emit = defineEmits(["ok"]);

// 状态参数
const state = reactive({
  // 当前编辑的ID
  id: 0,
  // 角色名称
  roleName: "",
  // 已选菜单
  menus: [],
  // 加载中
  isLoading: false,
  // 提交中
  confirmLoading: false,
  // 是否显示
  visible: false
});

// 组件
const treeRef = ref<TreeInstance>();

// 完整菜单数据
const menus = ref<OptionsType[]>([]);

// 弹窗开启
const handleOpen = async (options: FormModalOptions) => {
  state.isLoading = true;
  state.confirmLoading = false;
  if (typeof options.id === "number" && options.id) {
    state.id = options.id;
    const roleData = await $request.get.detail(options.id);
    state.roleName = roleData.roleName;
    state.menus = roleData.permissions;
    menus.value = [
      {
        value: "Home",
        label: "首页",
        disabled: true
      },
      ...(await $request.get.menusOptions())
    ];
    state.visible = true;
    setTimeout(() => {
      state.isLoading = false;
    }, 0);
  } else {
    message("数据读取失败，请刷新页面后重试", { type: "error" });
  }
};

// 提交
const handleSubmit = async () => {
  try {
    state.confirmLoading = true;
    const data = {
      menus: treeRef.value.getCheckedKeys()
    };
    await $request.put.action("menus", state.id, data);
    message("更新成功", { type: "success" });
    emit("ok");
    state.visible = false;
  } finally {
    state.confirmLoading = false;
  }
};

defineExpose({
  handleOpen
});
</script>

<template>
  <plus-dialog
    v-model="state.visible"
    title="角色权限"
    closeOnClickModal
    cancel-text="取消"
    confirm-text="确定"
    :confirm-loading="state.confirmLoading"
    @confirm="handleSubmit"
  >
    <plus-form-item
      v-model="state.roleName"
      label="角色名称"
      prop="roleName"
      :field-props="{
        disabled: true
      }"
    />
    <plus-form-item label="菜单设置" prop="menu">
      <template #plus-field-menu>
        <el-tree
          ref="treeRef"
          class="w-full"
          :data="menus"
          :default-checked-keys="['Home', ...state.menus]"
          :check-strictly="state.isLoading"
          show-checkbox
          default-expand-all
          node-key="value"
          check-on-click-node
          highlight-current
        />
      </template>
    </plus-form-item>
  </plus-dialog>
</template>

<style lang="scss" scoped>
//
</style>
